package com.yds.ydsdatasetbackend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yds.ydsdatasetbackend.annotation.AuthCheck;
import com.yds.ydsdatasetbackend.common.BaseResponse;
import com.yds.ydsdatasetbackend.common.Category;
import com.yds.ydsdatasetbackend.common.DeleteRequest;
import com.yds.ydsdatasetbackend.common.ResultUtils;
import com.yds.ydsdatasetbackend.constant.UserConstant;
import com.yds.ydsdatasetbackend.exception.BusinessException;
import com.yds.ydsdatasetbackend.exception.ErrorCode;
import com.yds.ydsdatasetbackend.exception.ThrowUtils;
import com.yds.ydsdatasetbackend.model.dto.file.FileQueryRequest;
import com.yds.ydsdatasetbackend.model.dto.file.FileUpdateRequest;
import com.yds.ydsdatasetbackend.model.dto.patient.*;
import com.yds.ydsdatasetbackend.model.entity.File;
import com.yds.ydsdatasetbackend.model.entity.Patient;
import com.yds.ydsdatasetbackend.model.entity.PatientGroup;
import com.yds.ydsdatasetbackend.model.entity.User;
import com.yds.ydsdatasetbackend.model.enums.FileFillEnum;
import com.yds.ydsdatasetbackend.model.vo.FileVO;
import com.yds.ydsdatasetbackend.model.vo.PatientGroupVO;
import com.yds.ydsdatasetbackend.model.vo.PatientVO;
import com.yds.ydsdatasetbackend.service.PatientGroupService;
import com.yds.ydsdatasetbackend.service.PatientService;
import com.yds.ydsdatasetbackend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/patient")
public class PatientController {


    @Resource
    private UserService userService;
    @Resource
    private PatientService patientService;


    /**
     * 添加病人
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.USER_LOGIN_STATE)
    public BaseResponse<PatientVO> addPatient(@RequestBody PatientAddRequest patientAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(StrUtil.isBlank(patientAddRequest.getPatientName()), ErrorCode.PARAMS_ERROR,"病人名称不能为空");
        return ResultUtils.success(patientService.addPatient(patientAddRequest, request));
    }

    /**
     * 删除病人
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.USER_LOGIN_STATE)
    public BaseResponse<Boolean> deletePatient(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = patientService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新图片（仅管理员可用）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.USER_LOGIN_STATE)
    public BaseResponse<Boolean> updatePatient(@RequestBody PatientUpdateRequest patientUpdateRequest, HttpServletRequest request) {
        if (patientUpdateRequest == null || patientUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        patientService.updatePatient(patientUpdateRequest, loginUser);
        return ResultUtils.success(true);   
    }

    /**
     * 根据 id 获取文件（仅管理员可用）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Patient> getPatientById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Patient patient = patientService.getById(id);
        ThrowUtils.throwIf(patient == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(patient);
    }

    /**
     * 根据 id 获取文件（封装类）
     */
    @GetMapping("/get/vo")
    public BaseResponse<PatientVO> getPatientVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Patient patient = patientService.getById(id);
        User loginUser = userService.getLoginUser(request);
        if(!Objects.equals(loginUser.getId(), patient.getUserId())){
            patient = null;
        }
        ThrowUtils.throwIf(patient == null, ErrorCode.NOT_FOUND_ERROR);

        PatientVO patientVO = patientService.getPatientVO(patient, request);
//        fileVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(patientVO);
    }


    /**
     * 分页获取文件列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Patient>> listPatientByPage(@RequestBody PatientQueryRequest patientQueryRequest, HttpServletRequest request) {

        long current = patientQueryRequest.getCurrent();
        long size = patientQueryRequest.getPageSize();
        // 查询数据库
        Page<Patient> patientPage = patientService.page(new Page<>(current, size),
                patientService.getQueryWrapper(patientQueryRequest));
        return ResultUtils.success(patientPage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.USER_LOGIN_STATE)
    public BaseResponse<Page<PatientVO>> listPatientVOByPage(@RequestBody PatientQueryRequest patientQueryRequest,
                                                       HttpServletRequest request) {
        long current = patientQueryRequest.getCurrent();
        long size = patientQueryRequest.getPageSize();
        // 设置用户信息
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "用户不存储在");
        patientQueryRequest.setUserId(loginUser.getId());

        // 限制爬虫
        ThrowUtils.throwIf(size > 50, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Patient> patientPage = patientService.page(new Page<>(current, size),
                patientService.getQueryWrapper(patientQueryRequest));
        // 获取封装类
        return ResultUtils.success(patientService.getPatientVOPage(patientPage, request));
    }


}
